<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="selFn">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 添加合同 -->
    <el-dialog title="添加合同" :visible="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="https://api-hmzs.itheima.net/tj/upload"
              name="file"
              :data="{type:'contract'}"
              :headers="{Authorization:`Bearer ${getToken()}`}"
              :on-success="successFn"
              :before-upload="beforeUpload"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAddFn()">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="exterpriseList" @expand-change="expandHandle">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status" />
              <el-table-column label="操作" width="180">
                <template>
                  <el-button size="mini" type="text">续租</el-button>
                  <el-button size="mini" type="text">退租</el-button>
                  <el-button size="mini" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id,0)">添加合同</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="editRent(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delFn(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
        <!--  </el-table-column></el-table-column> -->
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :page-size="params.pageSize"
        :total="total"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { getEnterpriseListAPI, delEnterpriseAPI, getRentBuildListAPI, createRentAPI, getRentListAPI } from '@/apis/enterprise'
import { getToken } from '@/utils/auth'
export default {
  name: 'Building',
  data() {
    return {
      exterpriseList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: ''
      },

      total: 0,
      rentDialogVisible: false, // 是否显示添加合同弹框
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },

      // 合同校验
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },

      buildList: [], // 楼宇租赁
      contractList: [] // 合同文件列表
    }
  },
  // 页面渲染
  mounted() {
    this.getExterpriseList()
    this.getRentBuildList()
  },
  methods: {
    getToken,
    // 页面资源
    async getExterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      // console.log(res)
      // ?.ke选链操作符
      // 作用：防止左边表达式为 undefined 时读取右侧属性报错
      this.exterpriseList = res.data?.rows.map((item) => {
        return {
          ...item,
          rentList: []
        }
      })
      this.total = res.data?.total
    },
    // 分页渲染
    pageChange(page) {
      this.params.page = page
      this.getExterpriseList()
    },
    // 查询
    selFn() {
      this.params.page = 1
      this.getExterpriseList()
    },
    // 编辑
    editRent(id) {
      this.$router.push({
        path: '/exterpriseAdd',
        query: {
          id
        }
      })
    },
    // 删除
    async delFn(id) {
      this.$confirm('确认删除该企业吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEnterpriseAPI(id)
        this.getExterpriseList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 点击添加合同
    addRent(id, type) {
      this.rentForm.enterpriseId = id
      this.rentForm.type = type
      this.rentDialogVisible = true
    },
    // 关闭
    closeDialog() {
      this.rentDialogVisible = false
    },
    // 租赁楼宇下拉菜单
    async getRentBuildList() {
      const res = await getRentBuildListAPI()
      console.log(res)
      this.buildList = res.data
    },
    // 依赖 el-upload 组件帮我传递上传到服务器成功后的反馈
    successFn(response, file, fileList) {
      console.log(response)
      console.log(file)
      console.log(fileList)

      this.rentForm.contractUrl = response.data.url
      this.rentForm.contractId = response.data.id
    },
    // 上传前验证
    beforeUpload(file) {
      const allowImgType = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同文件只能是 .doc, .pdf 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同文件大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 上传合同
    async confirmAddFn() {
      const obj = {
        ...this.rentForm,
        startTime: this.rentForm.rentTime[0],
        endTime: this.rentForm.rentTime[1]
      }
      delete obj.rentTime
      const res = await createRentAPI(obj)
      console.log(res)
    },
    // 展开查看列表
    async expandHandle(row, expandeRows) {
      // row:监听到展开时，当前点击的那行数据对象
      // expandeRows：当前已经展开的行的数据对象列表
      console.log(row)
      console.log(expandeRows)
      // 目标：只有展开行，展开时请求这家企业下属的合同列表
      const index = expandeRows.findIndex(obj => obj.id === row.id)
      if (index > -1) {
      // 刚展开
        const res = await getRentListAPI(row.id)
        console.log(res)
        res.data.forEach(obj => {
          row.rentList.push(obj)
        })
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
